
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include "Utility.h"

char g_logFileName[512];
FILE* g_hLogFile = NULL;
CUtility GUtility;

CUtility::~CUtility()
{
	if(g_hLogFile) fclose(g_hLogFile);
}

void CUtility::PrintLog(char log[1024])
{
	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	
	char buff[1024];
	_getcwd(buff,1024);
	sprintf(buff,"%s\\TinyImg_%.4u%.2u%.2u.log",buff,sysTime.wYear, sysTime.wMonth, sysTime.wDay);

	if(strcmp(buff,g_logFileName) != 0)
	{
		if(g_hLogFile)
		{
			fclose(g_hLogFile);
			Sleep(10);
		}
		memcpy(g_logFileName,buff,512);
		g_hLogFile=fopen(g_logFileName, "a+");
	}

	if(g_hLogFile)
	{
		sprintf(buff,"[%.2u:%.2u:%.2u:%u] %s",sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds, log);
		fprintf(g_hLogFile, "%s\n", buff);
		fflush(g_hLogFile);
	}
}

/**/
int FindFileDir(char* file)
{
	if(!file) return -1;

	int len = strlen(file);
	for (int i = len-1; i >= 0; i--){
		if (file[i] != '\\'){
			file[i] = '\0';
		}
		else break;
	}

	return 0;
}

int FindFullName(char* file)
{
	if(!file) return -1;

	int len = strlen(file);
	for (int i = len-1; i >= 0; i--){
		if (file[i] == '\\'){
			strcpy(file,&file[i+1]);
			return 0;
		}
	}

	return -1;
}

int FindFileName(char* file)
{
	if(!file) return -1;

	int len = strlen(file);
	for (int i = len-1; i >= 0; i--){
		if (file[i] == '\\'){
			strcpy(file,&file[i+1]);
			break;
		}
	}

	len = strlen(file);
	for (int i = len-1; i >= 0; i--){
		if (file[i] == '.'){
			file[i] = '\0';
			return 0;
		}
	}

	return -1;
}

int FindExtension(char* file)
{
	if(!file) return -1;

	int len = strlen(file);
	for (int i = len-1; i >= 0; i--){
		if (file[i] == '.'){
			strcpy(file,&file[i+1]);
			return 0;
		}
	}

	return -1;
}


int ToUpper(char* str)
{
	if(!str) return -1;
	int len = strlen(str);

	for (int i=0;i<len;i++){
		if (str[i]>='a' &&str[i]<='z'){
			str[i] -= 32;
		}
	}
	return 0;
}

int ToLower(char* str)
{
	if(!str) return -1;
	int len = strlen(str);

	for (int i=0;i<len;i++){
		if (str[i]>='A' &&str[i]<='Z'){
			str[i] += 32;
		}
	}
	return 0;
}

